package com.bidevalution.controller.api;

import com.bidevalution.business.context.StepStage;
import com.bidevalution.business.service.*;
import com.bidevalution.controller.dto.BeEvalutionExpertDTO;
import com.bidevalution.controller.util.RequestUtil;
import com.bidevalution.dao.entity.BeEvalutionExpert;
import com.bidevalution.dao.entity.BeSectionExpertInfo;
import com.bidevalution.dao.entity.BeSectionExpertProgress;
import com.bidevalution.dao.entity.BeSectionStep;
import com.bidevalution.service.layout.ColumnHeader;
import com.bidevalution.support.context.Constant;
import com.bidevalution.support.context.Constant.EnterpriseEnum;
import com.bidevalution.support.context.Constants;
import com.bidevalution.support.exception.BizException;
import com.bidevalution.support.util.StringUtil;
import com.qtp.common.core.TSUser;
import com.qtp.common.data.RedisAccess;
import com.qtp.core.model.Response;
import com.qtp.core.util.GsonUtil;
import com.qtp.core.util.IdsUtil;
import com.qtp.core.util.OConvertUtils;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author daizhifeng
 * @version V2.0
 * @Description: 专家评审明细
 * @date 2019年9月12日 下午4:43:19
 */
@Log4j2
@RestController
@RequestMapping("/beEvalutionExpert")
@Api(tags = "专家评审明细")
public class BeEvalutionExpertController extends BaseController {

    @Autowired
    private BeEvalutionExpertService beEvalutionExpertService;
    @Autowired
    private BeSectionExpertInfoService beSectionExpertInfoService;
    @Autowired
    private BeSectionStepService beSectionStepService;
    @Autowired
    private BeSectionExpertProgressService beSectionExpertProgressService;

    @Autowired
    private BeEvalutionOutcomeService beEvalutionOutcomeService;
    @Autowired
    private BeEvalutionColumnService beEvalutionColumnService;

    private static final String LAYOUT_CODE_LEFT = "Left";

    /**
     * 保存
     *
     * @param @param  isFinish
     * @param @param  beEvalutionExpertDTO
     * @param @return
     * @param @throws Exception 参数
     * @return Response<String> 返回类型
     * @throws
     * @Title: saveEvalutionExpert
     */
    @PostMapping("/saveEvalutionExpert")
    @ApiOperation(value = "保存专家评审明细", response = BeEvalutionExpertDTO.class)
    public Response<String> saveEvalutionExpert(
            @ApiParam(name = "isFinish", value = "保存标志,1提交，0保存", required = true) @RequestParam("isFinish") String isFinish,
            @RequestBody @ApiParam(name = "标段环节数据", value = "传入json格式", required = true) BeEvalutionExpertDTO beEvalutionExpertDTO) throws Exception {
        try {
            //目前布局为Left的都是环节信息数据，不需要保存到评审表，过滤这部分脏数据
            if (LAYOUT_CODE_LEFT.equals(beEvalutionExpertDTO.getLayoutCode())) {
                return Response.fail("布局代码为Left的不需要保存数据！");
            }
            System.out.println("*****" + GsonUtil.toJson(beEvalutionExpertDTO) + "******");
            String userGuid = RequestUtil.getHeader("userGuid");
            TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
            String sectionStepId = beEvalutionExpertDTO.getSectionStepId();
            if (tsUser != null) {
                List<ColumnHeader> columnList = beEvalutionExpertDTO.getColumnList();
                List<Map<String, Object>> dataList = beEvalutionExpertDTO.getDataList();
                if (columnList == null || dataList == null) {
                    return Response.fail("列字段或数据字段不能为空");
                }
                if (StringUtils.isEmpty(sectionStepId)) {
                    return Response.fail("环节id不可以为空");
                }
                BeSectionStep beSectionStep = beSectionStepService.getSectionStepBySeqId(sectionStepId);
                BeSectionExpertInfo beSectionExpertInfo = beSectionExpertInfoService.selectByLoginName(beEvalutionExpertDTO.getSectionId(), tsUser.getLoginName());
//				List<BeEvalutionExpert> beEvalutionExperts = new ArrayList<>();
//				BeEvalutionExpert beEvalutionExpert = null;
                //判断是否已经环节的数据操作记录
                BeSectionExpertProgress beSectionExpertProgress = beSectionExpertProgressService.selectByKey(sectionStepId, beSectionExpertInfo.getSeqId());
                if (beSectionExpertProgress == null) {
                    log.error("*****当前环节没有查询到操作记录*****");
                    return Response.fail("数据加载异常，请重新刷新");
                }
                String submitCode = beSectionExpertProgress.getSubmitCode();

//				String rowKey = "";//每行数据的唯一值
//				List<String> rowKeyList = new ArrayList<>();
				/*for (Map<String, Object> dataMap : dataList) {
					if(StringUtils.isEmpty(dataMap.get(Constant.EnterpriseEnum.EnterpriseId.getCode()))) {
						return Response.fail("enterpriseId参数不能为空");
					}
					if (StringUtils.isEmpty(dataMap.get("rowKey"))) {
						rowKey = IdsUtil.uuid().replaceAll("-", "");
					} else {
						rowKey = OConvertUtils.getString(dataMap.get("rowKey"));
						rowKeyList.add(rowKey);
					}
					for (ColumnHeader columnHeader : columnList) {
						if (!("rowKey").equals(columnHeader.getName())) {
							beEvalutionExpert = new BeEvalutionExpert();
							beEvalutionExpert.setSeqId(IdsUtil.uuid());
							beEvalutionExpert.setEnterpriseId(StringUtil.toString(dataMap.get(EnterpriseEnum.EnterpriseId.getCode())));
							beEvalutionExpert.setSectionStepId(sectionStepId);
							beEvalutionExpert.setSectionStepCode(beSectionStep.getStepCode());
							beEvalutionExpert.setSectionId(beEvalutionExpertDTO.getSectionId());
							beEvalutionExpert.setExpertId(beSectionExpertInfo.getSeqId());
							beEvalutionExpert.setLayoutCode(beEvalutionExpertDTO.getLayoutCode());
							beEvalutionExpert.setRowKey(rowKey);
							beEvalutionExpert.setSubmitCode(submitCode);
							beEvalutionExpert.setColumnCode(columnHeader.getCode());
							beEvalutionExpert
									.setColumnValue(OConvertUtils.getString(dataMap.get(columnHeader.getCode())));
							beEvalutionExperts.add(beEvalutionExpert);
						}
					}
				}*/

                //保存数据
                //旧接口
				/*beEvalutionExpertService.saveEvalutionExpert(beEvalutionExperts,
						beSectionStep, beSectionExpertInfo.getSeqId(), submitCode,isFinish,rowKeyList);*/
                if (Constants.STR_YES.equals(isFinish)) {
                    //简易法-合理低价审查，判断是否
                }
                synchronized ((beSectionStep.getSeqId() + "saveEvalutionExpert").intern()) {
                    //新接口
                    beEvalutionOutcomeService.save(dataList, columnList, beSectionStep, beSectionExpertInfo.getSeqId(), beEvalutionExpertDTO.getLayoutCode(), submitCode, isFinish, beEvalutionColumnService.selectList());
                }

                return Response.ok("保存成功");

            } else {
                return Response.fail("获取专家账号登录信息失败");
            }
        } catch (BizException e) {
            log.error(e.getMessage(), e);
            return Response.fail(e.getMessage());
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
            if (e.getErrorCode() == 10000) {
                return Response.fail(e.getMessage());
            } else {
                return Response.fail("数据保存异常，请联系管理员！");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("数据保存异常，请联系管理员！");
        }
    }
}
